﻿//Manimaran

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Tzync
{
    public class Profile
    {
        private const String ProfileSystemDataName = "SystemData";

        private String profileName;
        private String profilePath;
        private String rootAddressHost;
        private String rootAddressGuest;
        private bool firstSyncHost;
        private bool firstSyncGuest;
        private SystemType systemName;
        private bool hasHost;
        private bool hasGuest;
        private bool checkingForAvailability;
        String cpuIdHost, cpuIdGuest;

        /// <summary>
        /// Creation for first time on either computer.
        /// </summary>
        /// <param name="cpuID">Unique id for the computer</param>
        /// <param name="profileName">Name of the profile</param>
        /// <param name="rootAddress">Root address associated with the computer</param>
        public Profile(String cpuID, String profileName, String rootAddress)
        {
            this.profileName = profileName;
            hasHost = false;
            hasGuest = false;
            checkingForAvailability = false;
            systemName = SystemType.None;
            rootAddressHost = "";
            rootAddressGuest = "";
            cpuIdHost = "";
            cpuIdGuest = "";

            SetupFolder();
            WriteSystem(cpuID, rootAddress);            
            CheckSystem(cpuID);
        }

        /// <summary>
        /// To be called 3rd time onwards.
        /// </summary>
        /// <param name="cpuID">cpuID</param>
        /// <param name="profileName">name of the profile to be created</param>
        public Profile(String cpuID, String profileName)
        {
            this.profileName = profileName;
            systemName = SystemType.None;
            profilePath = Path.Combine(GlobalVariables.ProgramPath, GlobalVariables.ProjectName);
            profilePath = Path.Combine(profilePath, profileName);
            hasHost = false;
            hasGuest = false;
            rootAddressHost = "";
            rootAddressGuest = "";
            cpuIdHost = "";
            cpuIdGuest = "";
            checkingForAvailability = true;

            CheckSystem(cpuID);
        }

        /// <summary>
        /// Setting up of the profile. Creates the profile directory
        /// </summary>
        private void SetupFolder()
        {
            try
            {
                profilePath = Path.Combine(GlobalVariables.ProgramPath, GlobalVariables.ProjectName);
                profilePath = Path.Combine(profilePath, profileName);
                Directory.CreateDirectory(profilePath);
            }
            catch (DirectoryNotFoundException)
            {
                throw new DirectoryNotFoundException(profilePath, ActionType.Profile);
            }
        }

        public String ProfileName
        {
            get { return profileName; }
            set { profileName = value; }
        }

        public String ProfilePath
        {
            get { return profilePath; }
            set { profilePath = value; }
        }

        public bool FirstSyncHost
        {
            get { return firstSyncHost; }
            set { firstSyncHost = value; }
        }

        public bool FirstSyncGuest
        {
            get { return firstSyncGuest; }
            set { firstSyncGuest = value; }
        }

        public SystemType SystemName
        {
            get { return systemName; }
            set { systemName = value; }
        }

        public bool HasHost
        {
            get { return hasHost; }
            set { hasHost = value; }
        }

        public bool HasGuest
        {
            get { return hasGuest; }
            set { hasGuest = value; }
        }

        public String CPUIdHost
        {
            get { return cpuIdHost; }
            set { cpuIdHost = value; }
        }

        public String CPUIdGuest
        {
            get { return cpuIdGuest; }
            set { cpuIdGuest = value; }
        }

        public String RootAddressHost
        {
            get { return rootAddressHost; }
            set { rootAddressHost = value; }
        }

        public String RootAddressGuest
        {
            get { return rootAddressGuest; }
            set { rootAddressGuest = value; }
        }

        /// <summary>
        /// Stores the profile information in SystemData.
        /// </summary>
        /// <param name="cpuID">Unique id of the current computer</param>
        /// <param name="rootAddress">Root address of the folder associated with the computer</param>
        private void WriteSystem(String cpuID, String rootAddress)
        {
            int counter = 0;
            TextReader tr;
            StreamWriter SW;
            String input = "";            
            FileStream fs;
            String[] arrWords;

            String systemDataPath = Path.Combine(profilePath, ProfileSystemDataName);


            if (!File.Exists(systemDataPath))
            {
                //First time - write the current system's details.
                // create SystemData for the folder pairs                
                fs = File.Create(systemDataPath);
                fs.Close();

                SW = File.AppendText(systemDataPath);
                SW.WriteLine(cpuID + "|" + rootAddress);
                SW.Close();

                firstSyncHost = true;
            }
            else if (File.Exists(systemDataPath))
            {
                //Open file
                tr = new StreamReader(systemDataPath);
                while ((input = tr.ReadLine()) != null)
                {
                    if (input.Trim().Length != 0)
                    {
                        arrWords = input.Split('|');
                        if (counter == 0)
                        {
                            cpuIdHost = arrWords[0];
                        }
                        if (counter == 1)
                        {
                            cpuIdGuest = arrWords[0];
                        }
                        counter++;
                    }
                }
                tr.Close();

                // second time - write the second system's details.
                if (counter == 1 && cpuIdHost.CompareTo(cpuID) != 0 && !checkingForAvailability)
                {                    
                    SW = File.AppendText(systemDataPath);
                    SW.WriteLine(cpuID + "|" + rootAddress);
                    SW.Close();

                    firstSyncGuest = true;
                    cpuIdGuest = cpuID;
                }
            }
            
        }

        
        /// <summary>
        /// Used to determine which system (ie HOST or GUEST), if available for 2nd rootaddress and also to fill up the rootaddress
        /// </summary>
        /// <param name="cpuID">Unique id of the current computer</param>
        private void CheckSystem(String cpuID)
        {
            int counter = 0;
            TextReader tr;
            String input = "";
            String[] arrWords;

            String systemDataPath = Path.Combine(profilePath, ProfileSystemDataName);


             if (File.Exists(systemDataPath))
            {
                //Open file
                tr = new StreamReader(systemDataPath);
                while ((input = tr.ReadLine()) != null)
                {
                    if (input.Trim().Length != 0)
                    {
                        arrWords = input.Split('|');
                        if (counter == 0)
                        {
                            hasHost = true;
                            rootAddressHost = arrWords[1];
                            cpuIdHost = arrWords[0];
                            if (cpuID == arrWords[0])
                            {
                                systemName = SystemType.Host;
                            }
                        }
                        if (counter == 1)
                        {
                            hasGuest = true;
                            rootAddressGuest = arrWords[1];
                            cpuIdGuest = arrWords[0];
                            if (cpuID == arrWords[0])
                            {
                                systemName = SystemType.Guest;   
                            }
                        }
                        counter++;
                    }
                }
                tr.Close();
            }
        }

        /// <summary>
        /// This function is called when the rootFolder in either A(Host) or B(Guest) is moved/renamed
        /// </summary>
        public void WriteSystem()
        {
            String systemDataPath = Path.Combine(profilePath, ProfileSystemDataName);
            File.Delete(systemDataPath);

            StreamWriter SW;

            FileStream fs;
            fs = File.Create(systemDataPath);
            fs.Close();

            SW = File.AppendText(systemDataPath);
            SW.WriteLine(cpuIdHost + "|" + rootAddressHost);
            if(hasGuest)
             SW.WriteLine(cpuIdGuest + "|" + rootAddressGuest);
            SW.Close();
        }               
    }
}
